﻿@using Huirui.Cavan.Domain.MainBoundedContext.PurchaseModule
@model Huirui.Cavan.Presentation.ViewModel.PurchaseModule.IPurchaseViewModel
@{
    Layout = null;
}
@using (Html.BeginForm(ActionConst.ADD, ControllerConst.PURCHASE))
{
    <div class="tool_bar">
        <input id="purchase_save" type="submit" style="display: none;" />
        <input id="purchase_reset" type="reset" style="display: none" />
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-save'"
            onclick="javascript:$('#purchase_save').click()">保存</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-add'">新增</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-copy'">复制</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-delete'">删除</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-undo'"
            onclick="javascript:$('#purchase_reset').click()">重置</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-ok'" onclick="openWindow('selectStockWindowFromPurchaseOrder')">按订单入库</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-search'" onclick="addTab('入库列表','center_tt','@Url.Action(ActionConst.LIST, ControllerConst.STOCKINOUT)')">查询</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-print'">打印</a>
        <a href="#" class="easyui-linkbutton" data-options="plain:true,iconCls:'icon-collapse'"
            onclick="toggleHeard()">折叠/展开</a>
    </div>
    <table class="form_heard">
        <tr>
            <td class="c100">
                <label>
                    入库日期:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.PurchaseDate, new { id = "indate", @class = "Wdate", onfocus = "WdatePicker({minDate:'%y-%M-#{%d+1}'})" })
            </td>
            <td class="c100">
                <label>
                    采购人员:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.PurchaseEmployee.Id, new { id = "purchaseEmployeeCodeForPurchase" })
                @Html.HiddenFor(m => m.Item.PurchaseEmployee.Name, new { id = "purchaseEmployeeNameForPurchase" })
            </td>
            <td class="c100">
                <label>
                    入库单号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Id, new { id = "code" })
            </td>
            <td class="c10"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    供应商:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Supplier.Id, new { id = "supplierCodeForPurchase" })
            </td>
            <td colspan="2">
                @Html.TextBoxFor(m => m.Item.Supplier.Name, new { id = "supplierNameForPurchase", @class = "withprompt", @Value = "显示供应商名称" })
            </td>
            <td class="c100">
                <label>
                    供应商票据号:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.SupplierInvoiceNumber, new { id = "supplierInvoiceNumber" })
            </td>
            <td class="c10"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    币别:</label>
            </td>
            <td class="c160">
                @Html.DropDownList("currency", this.Model.Currencies, new { id = "currencyForPurchase" })
                @Html.HiddenFor(m => m.Item.Currency, new { id = "currencyValueForPurchase" })
            </td>
            <td class="c100">
                <label>
                    汇率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.CurrencyRate, new { id = "currencyRateForPurchase" })
            </td>
            <td class="c100">
                <label>
                    税率:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.TaxRate, new { id = "taxRateForPurchase" })
            </td>
            <td class="c10">
                @Html.Raw("%")
            </td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    仓库:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.WareHouse.Address, new { id = "wareHouseAddressForPurchase" })
                @Html.HiddenFor(m => m.Item.WareHouse.Id, new { id = "wareHouseCodeForPurchase" })
            </td>
            <td class="c100">
                <label>
                    联系人:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.Contact, new { id = "contactForPurchase" })
            </td>
            <td class="c100">
                <label>
                    电话:</label>
            </td>
            <td class="c160">
                @Html.TextBoxFor(m => m.Item.ContactTelephone, new { id = "contactTelephoneForPurchase" })
            </td>
            <td class="c10"></td>
        </tr>
        <tr>
            <td class="c100">
                <label>
                    备注:</label>
            </td>
            <td colspan="4">
                @Html.TextAreaFor(m => m.Item.Remark, new { id = "remarkForPurchase" })
            </td>
            <td colspan="2">
                <a>请选择常用备注</a>
            </td>
        </tr>
    </table>
    @Html.HiddenFor(m => m.StockInOutDetails, new { id = "stockInOutDetailsForPurchase" })
    @Html.HiddenFor(m => m.PurchaseOrders, new { id = "purchaseOrdersForPurchase"})
}
<table id="selectedStocksForPurchase" title="列表" toolbar="#purch_in_stock_tb">
</table>
<div id="purch_in_stock_tb">
    <a href="#" id="showSelectStockForPurchase" class="easyui-linkbutton" iconcls="icon-checked"
        plain="true" onclick="InitSelectStock('stocksForPurchase');openWindow('selectStockWindowForPurchase')">选择存货</a>
</div>

@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.STOCK, new { purpose = "ForPurchase" }); }
@{ Html.RenderAction(ActionConst.STOCKSFROMPURCHASEORDER, ControllerConst.STOCK); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.SUPPLIER, new { purpose = "ForPurchase" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.WAREHOUSE, new { purpose = "ForPurchase" }); }
@{ Html.RenderAction(ActionConst.SEARCH, ControllerConst.EMPLOYEE, new { purpose = "ForPurchase" }); }

<script type="text/javascript">
    $(function () {
        $('#selectedStocksForPurchase').datagrid({
            columns: [[
                { field: 'NoPrefixId', title: '存货编码', width: 100 },
                { field: 'Id', title: '存货编码', width: 100, hidden: true },
                { field: 'Name', title: '存货名称', width: 80 },
                { field: 'Specification', title: '规格', width: 60 },
                { field: 'Number', title: '数量', width: 100, editor: { type: 'text' } },
                { field: 'AssistantNumber', title: '辅助数量', width: 100 },
                { field: 'StandardPurchasePrice', title: '单价', width: 100 },
                { field: 'PurchaseAmount', title: '采购额', width: 80 },
                { field: 'LocalPurchaseAmount', title: '本币采购额', width: 80 },
                { field: 'TaxRate', title: '税率', width: 80, editor: { type: 'text' } },
                { field: 'TaxAmount', title: '税额', width: 80 },
                { field: 'Cost', title: '成本额', width: 80 },
                { field: 'UnitCost', title: '单位成本', width: 80 },
                { field: 'PurchaseOrderCode', title: '采购订单号', width: 80 },
                { field: 'Remark', title: '备注', width: 80 },
                { field: 'FromNumber', title: '', width: 80, hidden: true },
                { field: 'ToNumber', title: '', width: 80, hidden: true }
            ]]
        });

        $("#searchStockForPurchase").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksForPurchase').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        var currentIndex;
        var currentRow;
        var rowId;
        var number;
        var taxRateForPurchase = 0;
        var currencyRateForPurchase = 1;

        $("#doSelectStockForPurchase").bind("click", function () {
            $('#selectedStocksForPurchase').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksForPurchase').datagrid('getSelections');
            taxRateForPurchase = $("#taxRateForPurchase").val();
            if (taxRateForPurchase == '') {
                taxRateForPurchase = 0;
            }
            for (var i = 0; i < rows.length; i++) {
                insert(rows[i].NoPrefixId, rows[i].Id, rows[i].Name, rows[i].Specification, 0, rows[i].StandardPurchasePrice, 0, 0, taxRateForPurchase, 0, 0, 0, "", 'test', rows[i].FromNumber, rows[i].ToNumber);
            }
            closeWindow("selectStockWindowForPurchase");
        });

        $("#doSelectStocksFromPurchaseOrder").bind("click", function () {
            $('#selectedStocksForPurchase').datagrid('loadData', { total: 0, rows: [] });
            var rows = $('#stocksFromPurchaseOrder').datagrid('getSelections');
            taxRateForPurchase = $("#taxRateForPurchase").val();
            if (taxRateForPurchase == '') {
                taxRateForPurchase = 0;
            }
            if (rows.length > 0)
            {
                var selectedRow = new Object();
                selectedRow["selected"] = JSON.stringify(rows);

                $.post("/purchaseorder/listbyselect", selectedRow, function (data) {
                    if (data.total > 0) {
                        $("#purchaseEmployeeCodeForPurchase").val(data.rows[0].PurchaseEmployeeCode);
                        $("#supplierCodeForPurchase").val(data.rows[0].SupplierCode);
                        $("#supplierNameForPurchase").val(data.rows[0].SupplierName);
                        $("#supplierInvoiceNumber").val(data.rows[0].SupplierInvoiceNumber);
                        $("#currencyValueForPurchase").val(data.rows[0].Currency);
                        $("#currencyRateForPurchase").val(data.rows[0].CurrencyRate);
                        $("#wareHouseAddressForPurchase").val(data.rows[0].WareHouseAddress);
                        $("#wareHouseCodeForPurchase").val(data.rows[0].WareHouseCode);
                        $("#contactForPurchase").val(data.rows[0].Contact);
                        $("#contactTelephoneForPurchase").val(data.rows[0].ContactTelephone);
                        $("#taxRateForPurchase").val(data.rows[0].TaxRate);
                        $("#remarkremarkForPurchase").val(data.rows[0].Remark);
                    }
                    $("#purchaseOrdersForPurchase").val(JSON.stringify(data.rows));
                }, "JSON").error(function () {
                    $.messager.alert("提示", "网络异常，请稍候再试");
                });

                for (var i = 0; i < rows.length; i++) {
                    $('#stocksFromPurchaseOrder').datagrid('endEdit', $("#stocksFromPurchaseOrder").datagrid('getRowIndex', rows[i]));
                    insert(rows[i].NoPrefixId, rows[i].Code, rows[i].Name, rows[i].Specification, rows[i].CurrentStockInNumber, rows[i].CurrentStockInPrice, 0, 0, taxRateForPurchase, 0, 0, 0, rows[i].PurchaseOrderCode, '', rows[i].FromNumber, rows[i].ToNumber);
                    $('#stocksFromPurchaseOrder').datagrid('beginEdit', $("#stocksFromPurchaseOrder").datagrid('getRowIndex', rows[i]));
                }
                closeWindow('selectStockWindowFromPurchaseOrder');
            }
        });

        function insert(noPrefixId, id, name, specification, number, standardPurchasePrice, purchaseAmount, localPurchaseAmount, taxRateForPurchase, taxAmount, cost, unitCost, purchaseOrderCode, remark, fromNumber, toNumber) {
            var rows = $('#selectedStocksForPurchase').datagrid('getRows');
            index = -1;
            if (rows.length == 0) {
                index = 0;
            }
            else {
                index = rows.length;
            }

            $('#selectedStocksForPurchase').datagrid('insertRow', {
                index: index,
                row: {
                    NoPrefixId: noPrefixId,
                    Id: id,
                    Name: name,
                    Specification: specification,
                    Number: number,
                    StandardPurchasePrice: standardPurchasePrice,
                    PurchaseAmount: purchaseAmount,
                    LocalPurchaseAmount: localPurchaseAmount,
                    TaxRate: taxRateForPurchase,
                    TaxAmount: taxAmount,
                    Cost: cost,
                    UnitCost: unitCost,
                    PurchaseOrderCode: purchaseOrderCode,
                    Remark: remark,
                    FromNumber: fromNumber,
                    ToNumber: toNumber,
                    DefaultCurrency: '@HuiruiProject.UserSettings.DefaultCurrency.Rate'
                }
            });
            $('#selectedStocksForPurchase').datagrid('selectRow', index);
            $('#selectedStocksForPurchase').datagrid('beginEdit', index);

            var ed = $('#selectedStocksForPurchase').datagrid('getEditors', index);
            for (var i = 0; i < ed.length; i++) {
                var e = ed[i];
                if (e.field == "Number") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForPurchase').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        number = $(this).val();
                        if (parseFloat($("#currencyRateForPurchase").val()) > 0) {
                            currencyRateForPurchase = $("#currencyRateForPurchase").val();
                        }
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForPurchase').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "TaxRate") {
                                taxRateForPurchase = $(this).find("input").val();
                            }
                        });
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "PurchaseAmount") {
                                $(this).find("div").html(number * currentRow.StandardPurchasePrice);
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (1 - (100 / (parseFloat(taxRateForPurchase) + 100)))).toFixed(2));
                            }
                            if ($(this).attr("field") == "Cost") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (100 / (parseFloat(taxRateForPurchase) + 100))).toFixed(2));
                            }
                            if ($(this).attr("field") == "UnitCost") {
                                $(this).find("div").html(parseFloat(currentRow.StandardPurchasePrice * (100 / (parseFloat(taxRateForPurchase) + 100))).toFixed(2));
                            }
                            if ($(this).attr("field") == "AssistantNumber") {
                                $(this).find("div").html(parseFloat(currentRow.ToNumber * number / currentRow.FromNumber).toFixed(2));
                            }
                            if ($(this).attr("field") == "LocalPurchaseAmount") {
                                $(this).find("div").html(parseFloat(number * currentRow.StandardPurchasePrice * currentRow.DefaultCurrency / currencyRateForPurchase).toFixed(2));
                            }
                        });
                        $('#selectedStocksForPurchase').datagrid('unselectRow', currentIndex);
                        currentRow.Number = number;
                    })
                }
                else if (e.field == "TaxRate") {
                    $(e.target).attr("selectedStockRowIndex", index);
                    $(e.target).bind("click", function () {
                        $('#selectedStocksForPurchase').datagrid('selectRow', $(this).attr("selectedStockRowIndex"));
                    });
                    $(e.target).bind("blur", function () {
                        taxRateForPurchase = $(this).val();
                        currentIndex = $(this).attr("selectedStockRowIndex");
                        currentRow = $('#selectedStocksForPurchase').datagrid('getSelected');
                        rowId = $(this).parents().filter("tr").filter("[datagrid-row-index=" + currentIndex + "]").attr("id");
                        $("#" + rowId).find("td").each(function () {
                            if ($(this).attr("field") == "Number") {
                                number = $(this).find("input").val();
                            }
                            if ($(this).attr("field") == "TaxAmount") {
                                $(this).find("div").html(parseFloat((number * currentRow.StandardPurchasePrice) * (1 - (100 / (parseFloat(taxRateForPurchase) + 100)))).toFixed(2));
                            }
                        });
                        $('#selectedStocksForPurchase').datagrid('unselectRow', currentIndex);
                        currentRow.TaxRate = taxRateForPurchase;
                    })
                }
            }
        }

        $("form[action^='/purchase/add']").submit(function () {
            var rows = $('#selectedStocksForPurchase').datagrid('getRows');
            stockInOutDetailsForPurchase = "[";
            for (var i = 0; i < rows.length; i++) {
                if (i == (rows.length - 1)) {
                    stockInOutDetailsForPurchase = stockInOutDetailsForPurchase + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" : " + rows[i].StandardPurchasePrice + ", \"TaxRate\" :" + rows[i].TaxRate + ", \"Description\" : \"" + rows[i].PurchaseOrderCode + "\" }";
                }
                else {
                    stockInOutDetailsForPurchase = stockInOutDetailsForPurchase + "{ \"Stock\" : { \"Id\" : \"" + rows[i].Id + "\"}, \"Number\" : " + rows[i].Number + ", \"UnitCost\" : " + rows[i].StandardPurchasePrice + ", \"TaxRate\" :" + rows[i].TaxRate + ", \"Description\" : \"" + rows[i].PurchaseOrderCode + "\" }" + ",";
                }
            }
            stockInOutDetailsForPurchase = stockInOutDetailsForPurchase + "]";
            $("#stockInOutDetailsForPurchase").val(stockInOutDetailsForPurchase);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (data) {
                    if (data) {
                        alert(data.Messages[0]);
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#searchStockFromPurchaseOrder").submit(function () {
            var stockInStatues = '';
            $("input[type='checkbox'][name='stockInStatus']:checked").each(function () {
                stockInStatues = stockInStatues + $(this).val() + ",";
            });
            $("#stockInStatues").val(stockInStatues);
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#stocksFromPurchaseOrder').datagrid({
                            columns: [[
                                { field: 'IsSelected', title: '选择', width: 60, checkbox: true },
                                { field: 'SupplierName', title: '供应商', width: 80, align: 'right' },
                                { field: 'PurchaseOrderCode', title: '采购订单编号', width: 60 },
                                { field: 'Name', title: '存货', width: 80, align: 'right' },
                                { field: 'StockInStatus', title: '入库状态', width: 80, align: 'right' },
                                { field: 'DeliveryDate', title: '交货日期', width: 60 },
                                { field: 'Number', title: '订单数量', width: 100 },
                                { field: 'UnStockInNumber', title: '未入库数量', width: 80, align: 'center' },
                                { field: 'CurrentStockInNumber', title: '数量', width: 80, align: 'center', editor: 'numberbox' },
                                { field: 'CurrentStockInPrice', title: '价格', width: 100, editor: 'numberbox' },
                                { field: 'Address', title: '存货地点', width: 100 },
                                { field: 'FromNumber', title: '', width: 80, hidden: true },
                                { field: 'ToNumber', title: '', width: 80, hidden: true }
                            ]],
                            data: result
                        });

                        var rows = $('#stocksFromPurchaseOrder').datagrid('getRows');
                        for (var i = 0; i < rows.length; i++) {
                            $('#stocksFromPurchaseOrder').datagrid('beginEdit', i);
                        }
                    }
                    else {
                        $('#stocksFromPurchaseOrder').datagrid('loadData', { total: 0, rows: [] });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#supplierCodeForPurchase").bind("click", function () {
            InitSelectSupplier('suppliersForPurchase');
            openWindow("selectSupplierWindowForPurchase");
        });

        $("#searchSupplierForPurchase").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#suppliersForPurchase').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectSupplierForPurchase").bind("click", function () {
            var currentRow = $('#suppliersForPurchase').datagrid('getSelected');
            $("#supplierCodeForPurchase").val(currentRow.Id);
            $("#supplierNameForPurchase").val(currentRow.Name);
            closeWindow("selectSupplierWindowForPurchase");
        });

        $("#wareHouseAddressForPurchase").bind("click", function () {
            InitSelectWareHouse('wareHousesForPurchase');
            openWindow("selectWareHouseWindowForPurchase");
        });

        $("#searchWareHouseForPurchase").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#wareHousesForPurchase').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectWareHouseForPurchase").bind("click", function () {
            var currentRow = $('#wareHousesForPurchase').datagrid('getSelected');
            $("#wareHouseCodeForPurchase").val(currentRow.Id);
            $("#wareHouseAddressForPurchase").val(currentRow.Address);
            closeWindow("selectWareHouseWindowForPurchase");
        });

        $("#purchaseEmployeeCodeForPurchase").bind("click", function () {
            InitSelectEmployee('employeesForPurchase');
            openWindow("selectEmployeeWindowForPurchase");
        });

        $("#searchEmployeeForPurchase").submit(function () {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    if (result.total > 0) {
                        $('#employeesForPurchase').datagrid({
                            data: result,
                            checkOnSelect: true,
                            selectOnCheck: true
                        });
                    }
                },
                error: function () {
                    alert('系统繁忙，请稍候再试');
                }
            })

            return false;
        });

        $("#doSelectEmployeeForPurchase").bind("click", function () {
            var currentRow = $('#employeesForPurchase').datagrid('getSelected');
            $("#purchaseEmployeeCodeForPurchase").val(currentRow.Id);
            $("#purchaseEmployeeNameForPurchase").val(currentRow.Name);
            closeWindow("selectEmployeeWindowForPurchase");
        });

        $("select#currencyForPurchase").bind("change", function () {
            $("#currencyValueForPurchase").val($(this).find("option:selected").text());
            $("#currencyRateForPurchase").val($(this).val());
        });
    });
</script>
